<template>
  <div class="main-content pd16">

    <!--搜索栏-->
    <el-form class="search-form" ref="searchFormRef" :model="searchForm" :inline="true" label-width="70px">

      <el-form-item label="字典名称" prop="dictName" label-width="70px">
        <el-input v-model="searchForm.dictName" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="字典KEY" prop="dictKey" label-width="70px">
        <el-input v-model="searchForm.dictKey" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="字典值" prop="dictValue" label-width="70px">
        <el-input v-model="searchForm.dictValue" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="状态" prop="status" label-width="40px">
        <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width: 100px">
          <el-option v-for="dict in enu_common_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="searchData">搜索</el-button>
        <el-button icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>

    </el-form>

    <!--按钮组-->
    <div class="fx mgb12">
      <el-button type="primary" plain size="small" icon="Plus" @click="openAdd">新增字典</el-button>
      <el-button type="danger" plain size="small" icon="Delete" @click="deleteBatch">批量删除</el-button>
      <el-button type="warning" plain size="small" icon="Delete" @click="refreshCache">更新缓存</el-button>
    </div>

    <!--表格-->
    <el-table border highlight-current-row row-key="id"
              v-loading="option.loading" :data="option.tableData"
              @selection-change="selectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="字典名称" prop="dictName" width="260"></el-table-column>

      <el-table-column label="字典KEY" prop="dictKey" width="260">
        <template #default="scope">
          <span @click="clipboard(scope.row.dictKey,'字典KEY:复制成功')"> {{ scope.row.dictKey }}</span>
        </template>
      </el-table-column>

      <el-table-column label="字典值" prop="dictValue" :show-overflow-tooltip="true">
        <template #default="scope">
          <span @click="clipboard(scope.row.dictValue,'字典值:复制成功')"> {{ scope.row.dictValue }}</span>
        </template>
      </el-table-column>

      <el-table-column label="字典Tag预览">
        <template #default="scope">
          <el-tag class="pointer"
                  v-for="(item,index) in JSON.parse(scope.row.dictValue)"
                  :type="item.type"
                  :round="item.round"
                  style="margin-right: 5px"
                  :style="{color: item.color,borderColor: item.borderColor,background:item.background,borderRadius:item.borderRadius}">
            {{ item.label }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="排序" align="center" prop="sort"
                       :show-overflow-tooltip="true" width="80"></el-table-column>
      <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true" width="80">
        <template #default="scope">
          <dict-tag :options="enu_common_status" :value="scope.row.status"></dict-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="ct" width="170"></el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="100">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="openEdit(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--Dialog-->
    <el-dialog :title="option.dialogTitle" v-model="option.openDialog" width="820px" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>

      <el-form ref="formDataRef" size="default" :model="formData" :rules="formRules" label-width="100px">

        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="formData.dictName" placeholder="请输入" style="width: 600px"/>
        </el-form-item>

        <el-form-item label="字典KEY" prop="dictKey">
          <el-input v-model="formData.dictKey" placeholder="请输入" style="width: 600px"/>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" controls-position="right" :min="0" style="width: 600px"/>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" maxlength="500" placeholder="请输入" show-word-limit
                    :autosize="{ minRows: 2, maxRows: 4 }" style="width: 600px" type="textarea"/>
        </el-form-item>

        <!--        <el-form-item label="字典值" prop="dictValue">-->
        <!--          <el-input v-model="formData.dictValue" maxlength="4000" placeholder="请输入" show-word-limit-->
        <!--                    :autosize="{ minRows: 6, maxRows: 10 }" style="width: 600px;" type="textarea"/>-->
        <!--        </el-form-item>-->

        <el-form-item label="字典值预览" prop="dictValue">
          <div>
            <el-button size="small" plain type="primary" icon="Plus" @click="addOptionTag">
              添 加
            </el-button>
            <el-button size="small" plain icon="View" @click="openLookContent">
              查看内容
            </el-button>
            <el-button size="small" plain icon="Aim" @click="openCoverContent">
              文本覆盖
            </el-button>
            <br>

            <el-tag class="pointer"
                    v-for="(item,index) in formData.dictValue"
                    @click="()=>{option.clickIndex=index;}"
                    :type="item.type"
                    :round="item.round"
                    style="margin-right: 5px"
                    :style="{color: item.color,borderColor: item.borderColor,background:item.background,borderRadius:item.borderRadius}">
              {{ item.label }}
              <el-icon size="10">
                <Edit/>
              </el-icon>
            </el-tag>

            <el-form-item style="border: 1px dashed #807c7c;width: 600px;margin-top: 12px"
                          v-if="option.clickIndex!==-1">

              <el-form-item label="label" class="mg10" label-width="150">
                <el-input v-model="formData.dictValue[option.clickIndex].label" placeholder="请输入"
                          style="width: 400px"/>
              </el-form-item>

              <el-form-item label="value" class="mg10" label-width="150">
                <el-input v-model="formData.dictValue[option.clickIndex].value" placeholder="请输入"
                          style="width: 400px"/>
              </el-form-item>

              <el-form-item label="tag类型" class="mg10" label-width="150">
                <el-select v-model="formData.dictValue[option.clickIndex].type" placeholder="默认default" clearable
                           style="width: 400px">
                  <el-option label="default" value="default"/>
                  <el-option label="success" value="success"/>
                  <el-option label="info" value="info"/>
                  <el-option label="warning" value="warning"/>
                  <el-option label="danger" value="danger"/>
                </el-select>
              </el-form-item>

              <el-form-item label="tag圆角" class="mg10" label-width="150">
                <el-select v-model="formData.dictValue[option.clickIndex].round" placeholder="默认普通" clearable
                           style="width: 400px">
                  <el-option label="普通" :value="false"/>
                  <el-option label="椭圆" :value="true"/>
                </el-select>
              </el-form-item>

              <el-form-item label="自定义圆角(0px)" class="mg10" label-width="150">
                <el-input v-model="formData.dictValue[option.clickIndex].borderRadius" placeholder="请输入"
                          style="width: 400px" clearable/>
              </el-form-item>

              <el-form-item label="自定义字体色(#000)" class="mg10" label-width="150">
                <div class="fx_center_center">
                  <el-input v-model="formData.dictValue[option.clickIndex].color" placeholder="请输入"
                            style="width: 365px;font-size: 15px;margin-right: 5px" clearable/>
                  <el-color-picker v-model="formData.dictValue[option.clickIndex].color"/>
                </div>
              </el-form-item>

              <el-form-item label="自定义边框色(#000)" class="mg10" label-width="150">
                <div class="fx_center_center">
                  <el-input v-model="formData.dictValue[option.clickIndex].borderColor" placeholder="请输入"
                            style="width: 365px;font-size: 15px;margin-right: 5px" clearable/>
                  <el-color-picker v-model="formData.dictValue[option.clickIndex].borderColor" show-alpha/>
                </div>
              </el-form-item>

              <el-form-item label="自定义背景色(#000)" class="mg10" label-width="150">
                <div class="fx_center_center">
                  <el-input v-model="formData.dictValue[option.clickIndex].background" placeholder="请输入"
                            style="width: 365px;font-size: 15px;margin-right: 5px" show-alpha clearable/>
                  <el-color-picker v-model="formData.dictValue[option.clickIndex].background" show-alpha/>
                </div>
              </el-form-item>

              <span style="font-size: 10px;color: #CD4465;margin-left: 20px">
                *注意：自定义(字体、边框、背景)会分别覆盖"tag类型"内的属性；自定义圆角会覆盖"tag圆角"
              </span>

              <div class="fx_center_center" style="width: 100%;height: 50px">
                <el-button type="danger" size="small" plain @click="deleteOptionTag(option.clickIndex)">
                  删 除
                </el-button>
                <el-button size="small" plain @click="()=>{option.clickIndex=-1}">
                  关 闭
                </el-button>
              </div>

            </el-form-item>

          </div>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="()=>{option.openDialog=false}">取 消</el-button>
        <el-button v-if="option.dialogType==='add'" type="primary" @click="submitAdd">确 定</el-button>
        <el-button v-if="option.dialogType==='edit'" type="primary" @click="submitEdit">保 存</el-button>
      </template>

    </el-dialog>

    <!--文本内容-->
    <el-dialog :title="option.dialogTagTitle" v-model="option.openTagDialog" width="600px" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>

      <div v-if="option.dialogTagType==='lookTag'" style="width: 100%;word-wrap: break-word;">
        {{ JSON.stringify(formData.dictValue) }}
      </div>
      <el-form ref="formDataTagRef" size="default" :model="formData" :rules="formRules" label-width="65px">
        <el-form-item v-if="option.dialogTagType==='coverTag'" label="字典值" prop="dictValueStr">
          <el-input v-model="formData.dictValueStr" maxlength="4000" placeholder="请输入" show-word-limit
                    :autosize="{ minRows: 6, maxRows: 15 }" style="width: 100%;" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="()=>{option.openTagDialog=false}">取 消</el-button>
        <el-button v-if="option.dialogTagType==='lookTag'" type="primary" @click="lookContent">复 制</el-button>
        <el-button v-if="option.dialogTagType==='coverTag'" type="primary" @click="coverContent">确 定</el-button>
      </template>

    </el-dialog>


  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import {allDictOptionEnum, clearCache, deleteDict, insertDict, updateDict} from "@/common/api/system";
import $modal from "@/common/utils/modal";
import {blankStr, clipboard, copyNew} from "@/common/utils/kit";
import {asDict} from "@/common/api/common";
import DictTag from "@/common/component/DictTag.vue";

const {enu_common_status} = asDict("enu_common_status");

const {proxy} = getCurrentInstance();

const optionKey = {
  loading: false,
  openDialog: false,
  dialogTitle: "",
  dialogType: "",
  //
  dialogTagType: "",
  dialogTagTitle: "",
  openTagDialog: false,
  //
  tableData: [],
  selectIds: [],
  selectNames: [],
  pageSizes: [1, 10, 20, 50, 100],
  totalRow: 0,
  nowRoleId: 0,
  defaultChecked: [],
  allRole: [],
  clickItem: {},
  clickIndex: -1,
}

const formKey = {
  id: "",
  sort: 100,
  remark: "",
  moduleName: "",
  dictName: "",
  dictValue: [],
  dictValueStr: "",
  dictKey: "",
  type: "1",
}

const searchKey = {
  id: "",
  sort: 100,
  remark: "",
  moduleName: "",
  dictName: "",
  dictValue: "",
  dictKey: "",
}

const formRules = ref({
  dictName: [{required: true, message: "不能为空", trigger: "blur"}],
  dictValue: [{required: true, message: "不能为空", trigger: "blur"}],
  dictKey: [{required: true, message: "不能为空", trigger: "blur"}],
  dictValueStr: [{required: true, message: "不能为空", trigger: "blur"}],
});
const searchForm = ref(searchKey)
const formData = ref(formKey);
const option = ref(optionKey);

function resetForm() {
  formData.value = copyNew(formKey)
}

function resetSearch() {
  proxy.$refs["searchFormRef"].resetFields();
}

//页面加载完成回调
onMounted(() => {
  searchData()
})

function selectionChange(rows) {
  option.value.selectIds = rows.map(item => item.id);
  option.value.selectNames = rows.map(item => blankStr(item.moduleName, "") + "-" + blankStr(item.dictName, ""));
}

//搜索数据
function searchData() {
  option.value.loading = true;
  allDictOptionEnum(searchForm.value).then(res => {
    option.value.loading = false;
    option.value.tableData = res.data;
  })
}

function openAdd() {
  resetForm()
  option.value.dialogTitle = "新增字典";
  option.value.openDialog = true;
  option.value.dialogType = "add";
}

function openEdit(row) {
  //console.log(row)
  option.value.originOpenRow = row;
  option.value.dialogTitle = "编辑OptionTag";
  option.value.openDialog = true;
  option.value.dialogType = "edit";
  option.value.clickIndex = -1;
  formData.value = copyNew(row);
  formData.value.dictValue = JSON.parse(row.dictValue)
  formData.value.roleIds = formData.value.roleIds ? formData.value.roleIds.split(",") : []
}

function submitAdd() {
  proxy.$refs["formDataRef"].validate(valid => {

    if (valid) {
      let param = copyNew(formData.value)
      param.dictValue = JSON.stringify(formData.value.dictValue)
      insertDict(param).then(res => {
        if (res.success) {
          $modal.success();
          option.value.openDialog = false;
          searchData()
        }
      })
    }

  });
}

function submitEdit() {
  proxy.$refs["formDataRef"].validate(valid => {

    if (valid) {
      let param = copyNew(formData.value)
      param.dictValue = JSON.stringify(formData.value.dictValue)

      updateDict(param).then(res => {
        if (res.success) {
          //console.log(res)
          $modal.success();
          option.value.openDialog = false;
          searchData()
        }
      })
    }

  });
}

function refreshCache() {
  //console.log(ids)
  let content = `是否更新全部缓存？`
  $modal.confirmWarning(content)
      .then(async () => {
        clearCache().then((res) => {
          if (res.success) {
            $modal.success();
            searchData()
          }
        });
      }).catch(() => $modal.cancel());
}

function deleteBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }

  //console.log(ids)
  let content = `正在删除名称为【 ${option.value.selectNames.join("、")}】 的数据项，是否确定删除？ `
  $modal.confirmWarning(content)
      .then(async () => {
        let res = await deleteDict({ids: option.value.selectIds.join(",")})
        if (res.success) {
          $modal.success();
          searchData()
        }
      }).catch(() => $modal.cancel());
}

function addOptionTag() {
  formData.value.dictValue.push({})
}

function deleteOptionTag(index) {
  let content = `是否确定删除【${formData.value.dictValue[index].label}】？ `
  $modal.confirmWarning(content)
      .then(async () => {
        formData.value.dictValue.splice(index, 1)
        option.value.clickIndex = -1;
      }).catch(() => $modal.cancel());
}

function openLookContent() {
  option.value.openTagDialog = true
  option.value.dialogTagTitle = '字典值文本内容'
  option.value.dialogTagType = 'lookTag'
}

function openCoverContent() {
  option.value.openTagDialog = true
  option.value.dialogTagTitle = '覆盖字典值'
  option.value.dialogTagType = 'coverTag'
}

function lookContent() {
  clipboard(JSON.stringify(formData.value.dictValue), "标签内容：复制成功")
}

function coverContent() {
  proxy.$refs["formDataTagRef"].validate(valid => {
    formData.value.dictValue = JSON.parse(formData.value.dictValueStr);
  });
  option.value.openTagDialog = false
}

</script>

<style scoped lang="less">

</style>